package com.xxlie.auth.endpoint;

import com.xxlie.core.common.CacheKeyUtil;
import com.xxlie.auth.common.CommUtil;
import com.xxlie.core.common.ValidateUtil;
import com.xxlie.core.model.SmsBean;
import com.xxlie.core.model.View;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/common/sms")
public class SmsEndpoint {
    @Autowired
    CommUtil commUtil;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    RedisTemplate redisTemplate;

    @RequestMapping(value = "/send", method = RequestMethod.POST)
    public View send(HttpServletRequest request, HttpServletResponse response, @Validated @RequestBody SmsBean smsBean, BindingResult result) {
        //参数校验
        if (result.hasErrors()) {
            return View.ofError(ValidateUtil.first(result.getAllErrors()));
        }

        //【安全处理】用户短信发送次数过滤
        String filterKey = "filter_send_sms_phone_" + smsBean.getPhone();
        ValueOperations<String, Map> operations = redisTemplate.opsForValue();
        if (redisTemplate.hasKey(filterKey)) {
            Map filterMap = operations.get(filterKey);
            System.out.println(filterMap);
            int todaySendNum = Integer.parseInt(filterMap.get("todaySendNum").toString());
            long lastSendTime = Long.parseLong(filterMap.get("lastSendTime").toString());

            //1、判断发送的时间间隔
            if ((new Date().getTime() - lastSendTime) < 60000) {
                return View.ofError("短信发送间隔不足60秒，请稍后重试");
            } else if (!CommUtil.dateFormat(new Date(), "yyyy-MM-dd").equals(CommUtil.dateFormat(new Date(lastSendTime), "yyyy-MM-dd"))) {//2、判断发送的日差
                Map filter2Map = new HashMap();
                filter2Map.put("lastSendTime", new Date().getTime());
                filter2Map.put("todaySendNum", 1);
                operations.set(filterKey, filter2Map);
            } else if (todaySendNum >= 100) {//3、判断每日短信发送是不是超过总次数
                return View.ofError("短信发送超过次数");
            }
        }

        //生成短信验证码
        String code = commUtil.getSmsCode();

        //存入缓存使用
        stringRedisTemplate.opsForValue().set(CacheKeyUtil.PHONE_SMS + smsBean.getPhone(), code, 60 * 30, TimeUnit.SECONDS);

        //组装短信参数
        Map param = new HashMap();
        param.put("code", code);
        //发送短信
        Map sendResult = new HashMap();
        switch (smsBean.getType()) {
            case "0":
                sendResult = commUtil.sendLoginSms(smsBean.getPhone(), param, "");
                break;
            case "1":
                sendResult = commUtil.sendRegisterSms(smsBean.getPhone(), param, "");
                break;
            default:
                sendResult.put("code", "False");
                sendResult.put("message", "类型错误，发送失败");
        }

        System.out.println(sendResult);
        if (sendResult.get("code").equals("OK")) {
            //【安全处理】发送成功，记录发送次数
            if (redisTemplate.hasKey(filterKey)) {
                Map filterMap = operations.get(filterKey);
                int todaySendNum = Integer.parseInt(filterMap.get("todaySendNum").toString());

                //更新当前时间和总次数
                filterMap.put("lastSendTime", new Date().getTime());
                filterMap.put("todaySendNum", todaySendNum + 1);
                operations.set(filterKey, filterMap);
            } else {
                //第一次进入添加
                Map filterMap = new HashMap();
                filterMap.put("lastSendTime", new Date().getTime());
                filterMap.put("todaySendNum", 1);
                operations.set(filterKey, filterMap);
            }

            return View.ofOk("发送成功");
        } else {
            return View.ofError(sendResult.get("message").toString());
        }
    }

    @RequestMapping(value = "/send/test/{phone}")
    public View testPhone(HttpServletRequest request, HttpServletResponse response, @PathVariable("phone") String phone) {
        View view = new View(20000, "发送成功");

        String phone_cache = stringRedisTemplate.opsForValue().get("phone_" + phone);
        view.setData(phone_cache);
        return view;
    }

    @RequestMapping(value = "/send/test/time/{phone}")
    public View testTime(HttpServletRequest request, HttpServletResponse response, @PathVariable("phone") String phone) {
        View view = new View(20000, "发送成功");

        ValueOperations<String, Map> operations = redisTemplate.opsForValue();
        Map filterMap = new HashMap();
        filterMap.put("lastSendTime", "1507490942000");
        filterMap.put("todaySendNum", 6);

        String filterKey = "filter_send_sms_phone_" + phone;
        operations.set(filterKey, filterMap);

        return view;
    }
}